<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="​         原文链接：https:&#x2F;&#x2F;blog.csdn.net&#x2F;wzy1935&#x2F;article&#x2F;details&#x2F;128371394 ​        PySimpleGUI中，一般只使用按钮点击触发事件。但有时我们希望监测一些自定义事件，例如用户自己编写的回调事件。又或者，还有一些其他高级事件，例如键盘输入、鼠标移动…该怎么办呢？下面给一些解决方案： 自定义事件​        当我们需">
<meta property="og:type" content="article">
<meta property="og:title" content="pysimplegui高级和自定义事件">
<meta property="og:url" content="http://example.com/2024/01/20/pysimplegui%E9%AB%98%E7%BA%A7%E5%92%8C%E8%87%AA%E5%AE%9A%E4%B9%89%E4%BA%8B%E4%BB%B6/index.html">
<meta property="og:site_name" content="学无止境">
<meta property="og:description" content="​         原文链接：https:&#x2F;&#x2F;blog.csdn.net&#x2F;wzy1935&#x2F;article&#x2F;details&#x2F;128371394 ​        PySimpleGUI中，一般只使用按钮点击触发事件。但有时我们希望监测一些自定义事件，例如用户自己编写的回调事件。又或者，还有一些其他高级事件，例如键盘输入、鼠标移动…该怎么办呢？下面给一些解决方案： 自定义事件​        当我们需">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201120135.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201220473.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201231712.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201231656.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201509367.png">
<meta property="article:published_time" content="2024-01-20T02:55:19.000Z">
<meta property="article:modified_time" content="2024-01-20T02:55:19.000Z">
<meta property="article:author" content="xudonglei">
<meta property="article:tag" content="pysimplegui">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201120135.png">

<link rel="canonical" href="http://example.com/2024/01/20/pysimplegui%E9%AB%98%E7%BA%A7%E5%92%8C%E8%87%AA%E5%AE%9A%E4%B9%89%E4%BA%8B%E4%BB%B6/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>pysimplegui高级和自定义事件 | 学无止境</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">学无止境</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Do not bb, show me the example</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2024/01/20/pysimplegui%E9%AB%98%E7%BA%A7%E5%92%8C%E8%87%AA%E5%AE%9A%E4%B9%89%E4%BA%8B%E4%BB%B6/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="xudonglei">
      <meta itemprop="description" content="搬砖 嵌入式">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学无止境">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          pysimplegui高级和自定义事件
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2024-01-20 10:55:19" itemprop="dateCreated datePublished" datetime="2024-01-20T10:55:19+08:00">2024-01-20</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/python/" itemprop="url" rel="index"><span itemprop="name">python</span></a>
                </span>
            </span>

          
            <span id="/2024/01/20/pysimplegui%E9%AB%98%E7%BA%A7%E5%92%8C%E8%87%AA%E5%AE%9A%E4%B9%89%E4%BA%8B%E4%BB%B6/" class="post-meta-item leancloud_visitors" data-flag-title="pysimplegui高级和自定义事件" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2024/01/20/pysimplegui%E9%AB%98%E7%BA%A7%E5%92%8C%E8%87%AA%E5%AE%9A%E4%B9%89%E4%BA%8B%E4%BB%B6/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2024/01/20/pysimplegui%E9%AB%98%E7%BA%A7%E5%92%8C%E8%87%AA%E5%AE%9A%E4%B9%89%E4%BA%8B%E4%BB%B6/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>​         原文链接：<a target="_blank" rel="noopener" href="https://blog.csdn.net/wzy1935/article/details/128371394">https://blog.csdn.net/wzy1935/article/details/128371394</a></p>
<p>​        PySimpleGUI中，一般只使用按钮点击触发事件。但有时我们希望监测一些自定义事件，例如用户自己编写的回调事件。又或者，还有一些其他高级事件，例如键盘输入、鼠标移动…该怎么办呢？下面给一些解决方案：</p>
<h3 id="自定义事件"><a href="#自定义事件" class="headerlink" title="自定义事件"></a>自定义事件</h3><p>​        当我们需要手动触发事件循环时，可以使用 windows 的 write_event_value 方法：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201120135.png" style="zoom:80%;">

<p>​        我们可以在其他线程触发自定义事件：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"><span class="keyword">import</span> threading, time</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">looping</span>(<span class="params">window</span>):</span></span><br><span class="line">    called = <span class="number">0</span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        called += <span class="number">1</span></span><br><span class="line">        time.sleep(<span class="number">1</span>)</span><br><span class="line">        window.write_event_value(<span class="string">&#x27;loop_event&#x27;</span>, &#123;<span class="string">&#x27;called&#x27;</span>: called&#125;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">txt = sg.Text(<span class="string">&#x27;------&#x27;</span>, key=<span class="string">&#x27;test&#x27;</span>)</span><br><span class="line">layout = [[txt]]</span><br><span class="line">window = sg.Window(<span class="string">&#x27;test&#x27;</span>, layout, finalize=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">threading.Thread(target=looping, args=(window,)).start()</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: exit()</span><br><span class="line">    print(event, value) <span class="comment"># 打印所有触发的事件</span></span><br></pre></td></tr></table></figure>
<p>可以看到打印结果如下：</p>
<p>loop_event {‘loop_event’: {‘called’: 1}}<br>loop_event {‘loop_event’: {‘called’: 2}}<br>loop_event {‘loop_event’: {‘called’: 3}}<br>loop_event {‘loop_event’: {‘called’: 4}}<br>loop_event {‘loop_event’: {‘called’: 5}}<br>…</p>
<h3 id="控件交互事件"><a href="#控件交互事件" class="headerlink" title="控件交互事件"></a>控件交互事件</h3><p>​        按官方文档，当控件的 enable_events 为 true 时，当该元素被交互时(例如单击，输入一个字符)，则立即生成一个事件，导致 window.read() 调用返回。例如，对一个输入框，每当输入的字符更新时，都会触发事件。下面是示例代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"></span><br><span class="line">inp = sg.Input(enable_events=<span class="literal">True</span>, key=<span class="string">&#x27;input1&#x27;</span>)</span><br><span class="line">layout = [[inp]]</span><br><span class="line">window = sg.Window(<span class="string">&#x27;test&#x27;</span>, layout)</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: exit()</span><br><span class="line">    print(<span class="string">&#x27;EVENTS: &#x27;</span>,event)</span><br></pre></td></tr></table></figure>
<p>这时在每个在输入框里的键盘输入都会被检测到。</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201220473.png" style="zoom:67%;">

<h3 id="全局键盘事件"><a href="#全局键盘事件" class="headerlink" title="全局键盘事件"></a>全局键盘事件</h3><p>​        对于 window 组件可以开启 return_keyboard_events 对键盘进行全局监听。示例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"></span><br><span class="line">button = sg.Button(<span class="string">&#x27;test&#x27;</span>, key=<span class="string">&#x27;test&#x27;</span>)</span><br><span class="line">layout = [[button]]</span><br><span class="line">window = sg.Window(<span class="string">&#x27;test&#x27;</span>, layout, return_keyboard_events=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: exit()</span><br><span class="line">    print(event)</span><br></pre></td></tr></table></figure>
<p>这样就可以在event获取对应的keycode：</p>
<h3 id="bind高级事件"><a href="#bind高级事件" class="headerlink" title="bind高级事件"></a>bind高级事件</h3><p>​        然而有一些监听事件是PySimpleGUI做不到的。这时就需要调用组件的bind函数来绑定Tkinter的事件（因为PySimpleGUI是基于Tkinter开发的）。bind函数文档如下：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201231712.png" style="zoom:67%;">

<p>​        这里， bind_string 填待绑定的tkinter事件名（event sequences）。python-course站点给出了一些示例：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201231656.png" style="zoom:67%;">

<p>​        key_modifier 用来填写给event返回的附加值。例如，一个按钮控件的 key 是 btn，bind 函数里的 key_modifier 是_move，那么 bind 事件触发时，在事件循环里获取的event值就是 btn_move 。</p>
<p>​        下面是一个完整的bind示例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"></span><br><span class="line">button = sg.Button(<span class="string">&#x27;TEST&#x27;</span>, key=<span class="string">&#x27;test&#x27;</span>)  <span class="comment"># 必须设置 key</span></span><br><span class="line">layout = [[button]]</span><br><span class="line">window = sg.Window(<span class="string">&#x27;test&#x27;</span>, layout, finalize=<span class="literal">True</span>)  <span class="comment"># 必须设置 finalize</span></span><br><span class="line"></span><br><span class="line">button.bind(<span class="string">&#x27;&lt;Motion&gt;&#x27;</span>, <span class="string">&#x27;_move&#x27;</span>)  <span class="comment"># 绑定鼠标移动的事件</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: exit()</span><br><span class="line">    print(<span class="string">&#x27;EVENTS: &#x27;</span>, event)</span><br></pre></td></tr></table></figure>
<p>​        这里给按钮绑定了 <Motion> 事件，当鼠标在按钮上移动时，就会触发事件。因为 key_modifier 是 _move ，所以事件名为 test_move 。打印结果如下：</Motion></p>
<p>EVENTS:  test_move<br>EVENTS:  test_move<br>EVENTS:  test_move<br>EVENTS:  test_move<br>…</p>
<p>​        这里要注意的是，由于bind属于对组件的动态操作，所以调用时必须确保窗体构建完毕，因此需要给window 加上 finalize 。</p>
<h3 id="获取bind事件值"><a href="#获取bind事件值" class="headerlink" title="获取bind事件值"></a>获取bind事件值</h3><p>​        可惜，可以看出，在上面的示例中，我们在事件循环中只能获取事件名，但不能获取事件值。什么是事件值？一般来说，当一个事件触发时，我们还希望获得事件的具体情况。例如，当鼠标在控件上移动时，我们更希望知道鼠标的位置——不然只知道鼠标在移动有什么用？像这种事件的具体信息都会打包成一个事件值。<br>​        这时，我们可以使用控件的 user_bind_event 属性。当用户自定义的 bind 事件触发时，user_bind_event 会更新为本次事件的事件值。这里的事件值对象是tkinter里的 Event 类构造出的对象。可以通过 user_bind_event.x 和 user_bind_event.y 来获取鼠标当时的位置。看如下示例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"></span><br><span class="line">button = sg.Button(<span class="string">&#x27;test&#x27;</span>, key=<span class="string">&#x27;test&#x27;</span>)  <span class="comment"># 必须设置 key</span></span><br><span class="line">layout = [[button]]</span><br><span class="line">window = sg.Window(<span class="string">&#x27;test&#x27;</span>, layout, finalize=<span class="literal">True</span>)  <span class="comment"># 必须设置 finalize</span></span><br><span class="line"></span><br><span class="line">button.bind(<span class="string">&#x27;&lt;Motion&gt;&#x27;</span>, <span class="string">&#x27;_move&#x27;</span>)  <span class="comment"># 绑定鼠标移动的事件</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: exit()</span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;test_move&#x27;</span>:</span><br><span class="line">        print(<span class="string">&#x27;Mouse at:&#x27;</span>, button.user_bind_event.x, button.user_bind_event.y)</span><br></pre></td></tr></table></figure>
<p>​        鼠标在 button 上移动时， test_move 事件被触发，同时 button 的 user_bind_event 也会更新。此时便能获取鼠标的位置。输出如下：</p>
<p>Mouse at: 10 1<br>Mouse at: 11 1<br>Mouse at: 12 1<br>Mouse at: 13 1<br>Mouse at: 14 2<br>Mouse at: 15 3<br>…</p>
<h3 id="例1-滚轮事件"><a href="#例1-滚轮事件" class="headerlink" title="例1 - 滚轮事件"></a>例1 - 滚轮事件</h3><p>​        我们用两个例子来说明如何自定义事件。第一个例子是一个文本控件，当鼠标滚轮在文本上上滚动时，文本显示UP，反之显示DOWN。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"></span><br><span class="line">txt = sg.Text(<span class="string">&#x27;------&#x27;</span>, key=<span class="string">&#x27;test&#x27;</span>)</span><br><span class="line">layout = [[txt]]</span><br><span class="line">window = sg.Window(<span class="string">&#x27;test&#x27;</span>, layout, finalize=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">txt.bind(<span class="string">&#x27;&lt;MouseWheel&gt;&#x27;</span>, <span class="string">&#x27;_wheel&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: exit()</span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;test_wheel&#x27;</span>:</span><br><span class="line">        bind_event = txt.user_bind_event</span><br><span class="line">        print(bind_event)</span><br></pre></td></tr></table></figure>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201509367.png" style="zoom:67%;">

<p>​        不难看出，使用 delta 属性可以获知滚轮的位移。正数就是向上滚，反之就是向下。因此，加入判断即可：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> bind_event.delta &gt; <span class="number">0</span>:</span><br><span class="line">    txt.update(<span class="string">&#x27;UP&#x27;</span>)</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    txt.update(<span class="string">&#x27;DOWN&#x27;</span>)</span><br></pre></td></tr></table></figure>
<h3 id="例2-长按事件"><a href="#例2-长按事件" class="headerlink" title="例2 - 长按事件"></a>例2 - 长按事件</h3><p>​        接下来，我们为按钮编写一个长按事件，当按住按钮时，事件就一直被触发。</p>
<p>​        虽然Tkinter里没有长按事件的定义，但我们可以监控鼠标按下和松开的事件。这里用到的 bind_string 是 <Button-1> 和 <ButtonRelease-1> 。由于按钮的默认事件就是ButtonRelease，所以我们不用bind这个事件：</ButtonRelease-1></Button-1></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 绑定按钮按下的事件</span></span><br><span class="line">button.bind(<span class="string">&#x27;&lt;Button-1&gt;&#x27;</span>, <span class="string">&#x27;-down&#x27;</span>)</span><br><span class="line"><span class="comment"># button按钮松开的事件就是原生事件，无需绑定，其他元素需要</span></span><br><span class="line"><span class="comment"># button.bind(&#x27;&lt;ButtonRelease-1&gt;&#x27;, &#x27;-up&#x27;)</span></span><br></pre></td></tr></table></figure>
<p>​        通过这两个事件的触发，我们定义一个flag来表示按钮是否在按下状态。如果是，就反复触发按钮按下的事件。我们用额外的线程来实现：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">test_pressed_flag = <span class="literal">False</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">trigger_callback</span>(<span class="params">window</span>):</span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        time.sleep(<span class="number">0.1</span>)</span><br><span class="line">        <span class="keyword">if</span> test_pressed_flag:</span><br><span class="line">            window.write_event_value(<span class="string">&#x27;test-pressed&#x27;</span>, &#123;&#125;)</span><br><span class="line"></span><br><span class="line">threading.Thread(target=trigger_callback, args=(window,)).start()</span><br></pre></td></tr></table></figure>
<p>​        接着在事件循环中更新这个flag：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: exit()</span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;test-down&#x27;</span>:  <span class="comment"># mouse down</span></span><br><span class="line">        test_pressed_flag = <span class="literal">True</span></span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;test&#x27;</span>:  <span class="comment"># mouse up</span></span><br><span class="line">        test_pressed_flag = <span class="literal">False</span></span><br><span class="line">    print(event)</span><br></pre></td></tr></table></figure>
<p>​        完整代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"><span class="keyword">import</span> threading, time</span><br><span class="line"></span><br><span class="line">button = sg.Button(<span class="string">&#x27;test&#x27;</span>, key=<span class="string">&#x27;test&#x27;</span>)  <span class="comment"># 必须设置 key</span></span><br><span class="line">layout = [[button]]</span><br><span class="line">window = sg.Window(<span class="string">&#x27;test&#x27;</span>, layout, finalize=<span class="literal">True</span>)  <span class="comment"># 必须设置 finalize</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 绑定按钮按下的事件</span></span><br><span class="line">button.bind(<span class="string">&#x27;&lt;Button-1&gt;&#x27;</span>, <span class="string">&#x27;-down&#x27;</span>)</span><br><span class="line"><span class="comment"># button按钮松开的事件就是原生事件，无需绑定，其他元素需要</span></span><br><span class="line"><span class="comment"># button.bind(&#x27;&lt;ButtonRelease-1&gt;&#x27;, &#x27;-up&#x27;)</span></span><br><span class="line"></span><br><span class="line">test_pressed_flag = <span class="literal">False</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">trigger_callback</span>(<span class="params">window</span>):</span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        time.sleep(<span class="number">0.1</span>)</span><br><span class="line">        <span class="keyword">if</span> test_pressed_flag:</span><br><span class="line">            window.write_event_value(<span class="string">&#x27;test-pressed&#x27;</span>, &#123;&#125;)</span><br><span class="line"></span><br><span class="line">threading.Thread(target=trigger_callback, args=(window,)).start()</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: exit()</span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;test-down&#x27;</span>:  <span class="comment"># mouse down</span></span><br><span class="line">        test_pressed_flag = <span class="literal">True</span></span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;test&#x27;</span>:  <span class="comment"># mouse up</span></span><br><span class="line">        test_pressed_flag = <span class="literal">False</span></span><br><span class="line">    print(event)</span><br></pre></td></tr></table></figure>
<p>打印结果：</p>
<p>test-down<br>test-pressed<br>test-pressed<br>test-pressed<br>test-pressed<br>test</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/pysimplegui/" rel="tag"># pysimplegui</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2024/01/20/pysimplegui%E4%BA%8B%E4%BB%B6%E9%80%BB%E8%BE%91/" rel="prev" title="pysimplegui事件逻辑">
      <i class="fa fa-chevron-left"></i> pysimplegui事件逻辑
    </a></div>
      <div class="post-nav-item">
    <a href="/2024/01/20/pysimplegui%E6%A0%B7%E5%BC%8F%E7%BE%8E%E5%8C%96/" rel="next" title="pysimplegui样式美化">
      pysimplegui样式美化 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E4%BA%8B%E4%BB%B6"><span class="nav-number">1.</span> <span class="nav-text">自定义事件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%8E%A7%E4%BB%B6%E4%BA%A4%E4%BA%92%E4%BA%8B%E4%BB%B6"><span class="nav-number">2.</span> <span class="nav-text">控件交互事件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%85%A8%E5%B1%80%E9%94%AE%E7%9B%98%E4%BA%8B%E4%BB%B6"><span class="nav-number">3.</span> <span class="nav-text">全局键盘事件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#bind%E9%AB%98%E7%BA%A7%E4%BA%8B%E4%BB%B6"><span class="nav-number">4.</span> <span class="nav-text">bind高级事件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%8E%B7%E5%8F%96bind%E4%BA%8B%E4%BB%B6%E5%80%BC"><span class="nav-number">5.</span> <span class="nav-text">获取bind事件值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B1-%E6%BB%9A%E8%BD%AE%E4%BA%8B%E4%BB%B6"><span class="nav-number">6.</span> <span class="nav-text">例1 - 滚轮事件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B2-%E9%95%BF%E6%8C%89%E4%BA%8B%E4%BB%B6"><span class="nav-number">7.</span> <span class="nav-text">例2 - 长按事件</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">xudonglei</p>
  <div class="site-description" itemprop="description">搬砖 嵌入式</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">283</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">19</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">67</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xudonglei</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'BT0Qw9HcTpPv1a6cT1iDBXKz-gzGzoHsz',
      appKey     : 'LMCMh8v02JTMFAwKNRcgoizI',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : true,
      lang       : 'zh-CN' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
